<template>
	<view class="container">
		<view class="form-container">
			<view class="avatar-section">
				<image 
					:src="form.avatar || '/static/default-avatar.png'" 
					class="avatar"
					@click="chooseAvatar"
				></image>
				<text class="avatar-text">点击上方更换头像</text>
			</view>
			
			<view class="form-item">
				<text class="label">用户名</text>
				<input 
					v-model="form.name" 
					class="input" 
					placeholder="请输入用户名"
				/>
			</view>
			
			<view class="form-item">
				<text class="label">手机号</text>
				<input 
					v-model="form.phone" 
					class="input" 
					placeholder="请输入手机号"
					type="number"
				/>
			</view>
			
			<view class="form-item">
				<text class="label">性别</text>
				<picker 
					:value="sexIndex" 
					:range="sexList" 
					@change="onSexChange"
				>
					<view class="picker">
						{{ form.sex ? sexList[sexIndex] : '请选择性别' }}
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="label">身份证号</text>
				<input 
					v-model="form.idNumber" 
					class="input" 
					placeholder="请输入身份证号"
					maxlength="18"
				/>
			</view>
			
			<button class="save-btn" @click="handleSave">保存</button>
		</view>
	</view>
</template>

<script>
import api from '@/api/index'

export default {
	data() {
		return {
			form: {
				avatar: '',
				name: '',
				phone: '',
				sex: '',
				openid: '',
				idNumber: ''
			},
			sexList: ['男', '女'],
			sexIndex: 0
		}
	},
	onLoad() {
		this.getUserInfo()
	},
	methods: {
		// 获取用户信息
		async getUserInfo() {
			try {
				// 先尝试从本地存储获取openid
				const storedOpenid = uni.getStorageSync('openid')
				console.log('从存储获取的openid:', storedOpenid)
				
				// 获取本地存储的完整用户信息
				const storedUserInfo = uni.getStorageSync('userInfo')
				console.log('从存储获取的用户信息:', storedUserInfo)
				
				// 从后端获取用户信息
				const res = await api.user.getUserInfo()
				console.log('从后端获取的用户信息:', res)
				
				if (res.data) {
					// 尝试从多个可能的来源获取openid
					const openid = storedOpenid || 
						(storedUserInfo && (storedUserInfo.openid || storedUserInfo.open_id || storedUserInfo.userId)) ||
						(res.data.openid || res.data.open_id || res.data.userId) || 
						''
					
					console.log('最终使用的openid:', openid)
					
					// 如果有新的openid，更新本地存储
					if (openid && !storedOpenid) {
						uni.setStorageSync('openid', openid)
						console.log('更新本地存储的openid:', openid)
					}
					
					this.form = {
						...res.data,
						openid: openid,
						sex: res.data.gender === 1 ? '男' : '女'
					}
					this.sexIndex = this.form.sex === '女' ? 1 : 0
					
					console.log('最终的表单数据:', this.form)
				}
			} catch (error) {
				console.error('获取用户信息失败:', error)
			}
		},
		
		// 选择头像
		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				success: (res) => {
					this.form.avatar = res.tempFilePaths[0]
				}
			})
		},
		
		// 性别选择变化
		onSexChange(e) {
			this.sexIndex = e.detail.value
			this.form.sex = this.sexList[this.sexIndex]
		},
		
		// 保存用户信息
		async handleSave() {
			if (!this.form.name) {
				uni.showToast({
					title: '请输入用户名',
					icon: 'none'
				})
				return
			}
			
			if (!this.form.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}
			
			if (!this.form.sex) {
				uni.showToast({
					title: '请选择性别',
					icon: 'none'
				})
				return
			}
			
			if (!this.form.idNumber) {
				uni.showToast({
					title: '请输入身份证号',
					icon: 'none'
				})
				return
			}
			
			// 确保openid存在
			if (!this.form.openid) {
				// 尝试从多个来源获取openid
				const storedOpenid = uni.getStorageSync('openid')
				const storedUserInfo = uni.getStorageSync('userInfo')
				const openid = storedOpenid || 
					(storedUserInfo && (storedUserInfo.openid || storedUserInfo.open_id || storedUserInfo.userId))
				
				console.log('保存时获取到的openid:', openid)
				
				if (openid) {
					this.form.openid = openid
				} else {
					console.error('无法获取用户ID')
					uni.showToast({
						title: '用户信息不完整，请重新登录',
						icon: 'none'
					})
					// 可以选择跳转到登录页面
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
					return
				}
			}
			
			// 创建要发送的数据对象，将性别转换为数字
			const submitData = {
				...this.form,
				sex: this.form.sex === '男' ? 1 : 0
			}
			
			console.log('准备提交的数据:', submitData)
			
			try {
				const result = await api.user.updateUserInfo(submitData)
				console.log('更新接口返回结果:', result)
				
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('保存用户信息失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style scoped>
.container {
	padding: 30px 20px;
	background: linear-gradient(180deg, #f0f2f5 0%, #ffffff 100%);
	min-height: 100vh;
}

.form-container {
	background: #fff;
	border-radius: 20px;
	padding: 40px 30px;
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
	max-width: 420px;
	margin: 0 auto;
	position: relative;
	overflow: hidden;
}

.form-container::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 4px;
	background: linear-gradient(90deg, #007AFF, #cc73a7);
}

.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 40px;
	position: relative;
}

.avatar {
	width: 120px;
	height: 120px;
	border-radius: 50%;
	margin-bottom: 15px;
	background-color: #f5f5f5;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	border: 3px solid #fff;
	transition: all 0.3s ease;
}

.avatar:active {
	transform: scale(0.98);
}

.avatar-text {
	font-size: 14px;
	color: #666;
	font-weight: 500;
	background: #f8f9fa;
	padding: 6px 16px;
	border-radius: 20px;
	transition: all 0.3s ease;
}

.avatar-text:active {
	background: #f0f0f0;
}

.form-item {
	margin-bottom: 25px;
	position: relative;
}

.label {
	display: block;
	margin-bottom: 8px;
	color: #333;
	font-size: 14px;
	font-weight: 600;
	padding-left: 4px;
}

.input {
	width: 100%;
	height: 46px;
	border: 1px solid #eaeaea;
	border-radius: 12px;
	padding: 0 16px;
	font-size: 15px;
	background-color: #f8f9fa;
	transition: all 0.3s ease;
	max-width: 320px;
	margin: 0 auto;
	display: block;
	box-sizing: border-box;
}

.input:focus {
	border-color: #007AFF;
	background-color: #fff;
	box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
	outline: none;
}

.picker {
	width: 100%;
	height: 46px;
	border: 1px solid #eaeaea;
	border-radius: 12px;
	padding: 0 16px;
	line-height: 46px;
	font-size: 15px;
	background-color: #f8f9fa;
	color: #333;
	max-width: 320px;
	margin: 0 auto;
	display: block;
	box-sizing: border-box;
	transition: all 0.3s ease;
}

.picker:active {
	border-color: #007AFF;
	background-color: #fff;
}

.save-btn {
	width: 280px;
	height: 44px;
	background: linear-gradient(90deg, #007AFF, #cc73a7);
	color: #fff;
	border-radius: 12px;
	font-size: 15px;
	font-weight: 600;
	margin: 40px auto 0;
	box-shadow: 0 6px 15px rgba(0, 122, 255, 0.2);
	transition: all 0.3s ease;
	display: block;
	border: none;
	position: relative;
	overflow: hidden;
}

.save-btn::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(rgba(255, 255, 255, 0.1), transparent);
}

.save-btn:active {
	transform: translateY(1px);
	box-shadow: 0 4px 10px rgba(0, 122, 255, 0.15);
}

.input[disabled] {
	background-color: #f0f0f0;
	color: #666;
	cursor: not-allowed;
}
</style>